package com.wanger.swa.config.filter;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: wanger
 * @Date: 2024/9/16 3:49
 * @Description:
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 配置静态资源访问路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 静态资源访问路径和存放路径配置
        registry.addResourceHandler("sw/static/**").addResourceLocations("classpath:/static/", "classpath:/public/");
        // swagger访问配置
        registry.addResourceHandler("sw/**").addResourceLocations("classpath:/META-INF/resources/", "classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 设置StringHttpMessageConverter解决中文乱码
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));

        // 创建一个Jackson的ObjectMapper，配置它允许未知属性
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  // 忽略未知属性

        // 使用自定义的ObjectMapper，避免 JSON 反序列化时报错
        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
        jacksonConverter.setSupportedMediaTypes(CollUtil.toList(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN));

        converters.add(jacksonConverter);
    }
}
